package com.beta.resource.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.springframework.core.io.ClassPathResource;

import com.beta.resource.model.Metal;

public class BaseFile {
    private static final String MODE_WRITE = "rw";
    private static final int MAX_CAPACITY = 128;
    private static final int NETFILE_COMMECT_TIMEOUT = 3 * 1000;


    public static boolean loadFile(String path, onStatusChange listener, Object data) throws IOException {
        byte[] buffer = null;
        String mime = null;
        File localFile = null;
        HttpURLConnection conn = null;
        BufferedInputStream bufferedInputStream = null;
        int offset = 0;
        int len = 0;
        boolean allload = false;
        boolean isNetFile = BaseString.isUrl(path);
        if (listener == null) {
            return true;
        }
        if (isNetFile) {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(NETFILE_COMMECT_TIMEOUT);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            mime = conn.getContentType();
            len = conn.getContentLength();
            bufferedInputStream = new BufferedInputStream(conn.getInputStream());
        } else {
            localFile = new File(path);
            if (!localFile.exists() || !localFile.isFile()) {
                return false;
            }
            bufferedInputStream = new BufferedInputStream(new FileInputStream(localFile));
            bufferedInputStream.mark(0);
            mime = URLConnection.guessContentTypeFromStream(bufferedInputStream);
            len = bufferedInputStream.available();
            if(bufferedInputStream.markSupported()){
                bufferedInputStream.reset();
            }
        }
        if (mime == null) {
            buffer = new byte[MAX_CAPACITY];
            len = MAX_CAPACITY;
        } else if (mime.startsWith("image")) {
            allload = true;
            buffer = new byte[len + 1];
        }
        while ((len = bufferedInputStream.read(buffer, offset, len)) != -1) {
            if (allload) {
                offset += len;
                len = buffer.length - offset;
            } else if (listener != null) {
                listener.onLoad(Metal.RESPOND_MIME_TXT, new String(buffer, offset, len), data);
                len = MAX_CAPACITY;
            }
        }
        bufferedInputStream.close();
        if (isNetFile) {
            conn.disconnect();
        }
        if (allload && listener != null) {
            listener.onLoad((Metal.RESPOND_MIME_HTML | Metal.RESPOND_MIME_IMG), BaseString.encodeBase64(buffer), data);
        }
        return true;
    }

    public static boolean loadResourceFile(String path, onStatusChange listener, Object data) throws IOException {
        if(listener == null){
            return true;
        }
        File rfile = new ClassPathResource(path).getFile();
        byte[] buffer = new byte[MAX_CAPACITY];
        int len = 0;
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(rfile));
        while ((len = bufferedInputStream.read(buffer, 0, MAX_CAPACITY)) != -1) {
            listener.onLoad(Metal.RESPOND_MIME_TXT, new String(buffer, 0, len), data);
            len = MAX_CAPACITY;
        }
        bufferedInputStream.close();
        return true;
    }

    public static String createNewFile(String path, String filename, boolean override){
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, filename + ".py");
        while (file.exists() && !override) {
            file = new File(path, filename + Time.getUTCTime("_yyyy_MM_dd-HH_mm_ss") + ".py");
        }
        return file.getAbsolutePath();
    }

    public static int appendFile(String path, byte[]buffer, long offset){
        int length = 0;
        File file = new File(path);
        RandomAccessFile raf = null;
        boolean isOpen = false;
        try {
            raf = new RandomAccessFile(file, MODE_WRITE);
            isOpen = true;
            raf.seek(offset);
            raf.write(buffer);
            length = buffer.length;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isOpen) {
                    raf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return length;
    }
}
